﻿# -*- coding: utf-8 -*-
'''
WOT cache parser version 0.2
Igor aka Byte, 08/2012
'''
import sys
import pickle
import struct
import datetime
import os

__VER__ = 0.1
__DEBUG__ = True
__LANG__ = 'en'
__CACHEDIR__ = False
__OUTTOCONSOLE__ = False
__ONETANK__ = False
_txtFile = 'tanks.stat'
_xmlFile = 'tanks_stat.xml'
#определения для разбора строки с данными
_version = 'H'
warrior = 'H'
invader = 'H'
sniper = 'H'
defender = 'H'
steelwall = 'H'
supporter = 'H'
scout = 'H'
evileye = 'H'
battleHeroes = 'H'
treesCut = 'H'
maxXP = 'H'
sniperSeries = 'H'
maxSniperSeries = 'H'
invincibleSeries = 'B'
maxInvincibleSeries = 'B'
diehardSeries = 'B'
maxDiehardSeries = 'B'
killingSeries = 'B'
maxKillingSeries = 'B'
piercingSeries = 'B'
maxPiercingSeries = 'B'
maxFrags = 'B'
xp = 'I'
company_xp = 'I'
clan_xp = 'I'
battlesCount = 'I'
company_battlesCount = 'I'
clan_battlesCount = 'I'
wins = 'I'
company_wins = 'I'
clan_wins = 'I'
losses = 'I'
company_losses = 'I'
clan_losses = 'I'
survivedBattles = 'I'
company_survivedBattles = 'I'
clan_survivedBattles = 'I'
winAndSurvived = 'I'
lastBattleTime = 'I'
frags = 'I'
company_frags = 'I'
clan_frags = 'I'
frags8p = 'I'
fragsBeast = 'I'
shots = 'I'
company_shots = 'I'
clan_shots = 'I'
hits = 'I'
company_hits = 'I'
clan_hits = 'I'
spotted = 'I'
company_spotted = 'I'
clan_spotted = 'I'
damageDealt = 'I'
company_damageDealt = 'I'
clan_damageDealt = 'I'
damageReceived = 'I'
company_damageReceived = 'I'
clan_damageReceived = 'I'
capturePoints = 'I'
company_capturePoints = 'I'
clan_capturePoints = 'I'
droppedCapturePoints = 'I'
company_droppedCapturePoints  = 'I'
clan_droppedCapturePoints = 'I'
battleLifeTime = 'I'
creationTime = 'I'
maxXPVehicle = 'I'
maxFragsVehicle = 'I'
medalKay = 'B'
medalCarius = 'B'
medalKnispel = 'B'
medalPoppel = 'B'
medalAbrams = 'B'
medalLeClerc = 'B'
medalLavrinenko = 'B'
medalEkins = 'B'
medalWittmann = 'H'
medalOrlik = 'H'
medalOskin = 'H'
medalHalonen = 'H'
medalBurda = 'H'
medalBillotte = 'H'
medalKolobanov = 'H'
medalFadin = 'H'
medalRadleyWalters = 'H'
medalLafayettePool = 'H'
medalBrunoPietro = 'H'
medalTarczay = 'H'
medalPascucci = 'H'
medalDumitru = 'H'
medalLehvaslaiho = 'H'
medalNikolas = 'H'
beasthunter = 'H'
mousebane = 'H'
tankExpert = 'B'
titleSniper = 'B'
invincible = 'B'
diehard = 'B'
raider = 'H'
handOfDeath = 'B'
armorPiercer = 'B'
kamikaze = 'H'
lumberjack = 'H'
markOfMastery = 'B'

totalTanks = 0	#по скольким танкам сделана запись
tankToOut = ''
saveToFileMes = False	#чтобы вывести сообщение о том, что файл записан

#словарь танков и их индентификаторов
tanksID = {u'АТ-1': (2, 5121), 'ELC AMX': (2, 14145), 'PzKpfw 35 (t)': (2, 785), 'T2 Medium tank': (2, 5665), u'Т-54': (2, 7937), 'Hotchkiss H35': (2, 1345),  'Leichttraktor': (2, 3089), u'СУ-85': (2, 257), \
			u'БТ-2': (2, 1025), 'T1 Cunningham': (2, 545),'AMX 12t': (2, 6465), u'МС-1': (2, 3329), u'БТ-7': (2, 769), u'Т-26': (2, 4609), 'AMX 13 90': (2, 4929), 'T29': (2, 3873), u'Т-34': (2, 1), \
			'VK 3001 (P)': (2, 7185), 'M6': (2, 801), 'PzKpfw IV': (2, 17), 'T1 heavy': (2, 3361), u'Т-28': (1537), "AMX 40": (2, 2881), 'PzKpfw 38 nA': (2, 8209), 'M3 Lee': (2, 3105), \
			u'А-20': (2, 2940), u'СУ-18': (2, 3841), 'PzKpfw 38 (t)': (2, 3345), 'AMX 38': (2, 5953), u'ИС': (2, 513), 'Lorraine 40 t': (2, 5697), 'Type 59': (2, 49), \
			u'СУ-85Б': (2, 6913), u'Т-50-2': (2, 9729), 'Churchill': (2, 51713), 'T34': (2, 2849), 'M103': (2, 9505),  u'Т-34-85': (2, 2561), u'ИС-3': (2, 5377), 'T32': (2, 4385), \
			u'ИС-4': (2, 6145), u'Т-50': (2, 9473), u'СУ-26': (2, 7681), u'ИС-8': (2, 11521), u'КВ-1': (2, 11777), 'T110E5': (2, 10785), u'ИС-7': (2, 7169), 'RenaultFT': (2, 577), \
			u'СУ-76': (2, 6401), u'КВ-4': (2, 11009), 'M2 Medium Tank': (2, 4897), u'СУ-14': (2, 4097), u'Т-46': (2, 3073), u'А-20': (2, 2049), u'КВ-3': (2, 5889), \
			'VK4502 (P) Ausf.A': (2, 10513), 'T30': (2, 2593), u'Т-28': (2, 1537), u'СУ-5': (2, 4865), 'AMX 13 75': (2, 5185), u'СУ-8': (2, 5633), u'Т-43': (2, 6657), \
			u'Т-44': (2, 4353), u'Т-150': (2, 11265), u'С-51': (2, 1793), u'СУ-152': (2, 2305), u'КВ-1С': (2, 2817), u'СУ-100': (2, 3585), u'СУ-18': (2, 3841), \
			u'ИСУ-152': (2, 7425), u'Об. 704': (2, 8193), u'Об. 212': (2, 8449), u'Об. 261': (2, 8705), u'КВ-13': (2, 8961), u'ИС-6': (2, 9217), u'СТ-1': (2, 10753), \
			u'Об. 268': (2, 13569), u'Т-62А': (2, 13825), u'КВ-220': (2, 51201), u'Matilda': (2, 51457), u'Valentine': (2, 52481), u'А-32': (2, 52993), u'КВ-5': (2, 53249), \
			u'Tetrarch': (2, 54529), u'М3 Стюарт': (2, 52737), u'БТ-СВ': (2, 52481), u'Т-127': (2, 53505), 'T14': (2, 33), 'M3 Stuart': (2, 289), 'M4 Sherman': (2, 1057), \
			'M4A3E8 Sherman': (2, 1313), 'T-20': (2, 1569), 'M2 Light Tank': (2, 1825), 'T57': (2, 2081), 'T23': (2, 2337),  'M7 Priest': (2, 3617), 'M41': (2, 4129), \
			'M37': (2, 4641), 'M5 Stuart': (2, 5153), 'M7': (2, 5409), 'M26 Pershing': (2, 5921), 'T18': (2, 6177), 'T82': (2, 6433), 'M10 Wolverine': (2, 6945), 'M36 Slagger': (2, 7201), \
			'M40M43': (2, 7457), 'T40': (2, 7713), 'M12': (2, 7969), 'T28': (2, 8225), 'T92': (2, 8481), 'T95': (2, 8737), 'M46 Patton': (2, 8993), 'T25 AT': (2, 9249), \
			'M24 Chaffee': (2, 9761), 'M8A1': (2, 10273), 'T49': (2, 10529), 'T25/2': (2, 11041), 'T28 Prot.': (2, 11297), 'M18 Hellcat': (2, 11533), 'T110E4': (2, 13089), \
			'SuperPershing': (2, 13345), 'T110E3': (2, 13857), 'M48A1': (2, 14133), 'T2 Light Tank': (2, 51489), 'Ram-II': (2, 51745), 'MTLS-1G14': (2, 52001), \
			'M4A2E4': (2, 52257), 'M6A2E1': (2, 52513), 'M22 Locust': (2, 52767), 'Hummel': (2, 273),  'StuGIII': (2, 1041), 'PzKpfw V Panther': (2, 1297), 'JagdPz IV': (2, 1553), \
			'Hetzer': (2, 1809), 'PzKpfw II': (2, 2065), 'VK3601H': (2, 2321), 'VK3001H': (2, 2577), 'Sturmpanzer I Bison': (2, 2833), 'JagdPz IV': (2, 3601), \
			'Jagdpanther': (2, 3857), 'VK3002DB': (2, 4113), 'PzKpfw III': (2, 4369), 'Sturmpanzer II': (2, 4625), 'Tiger II': (2, 5137), 'VK1602': (2, 5393), 'Grille': (2, 5649), \
			'Wespe': (2, 5905), 'PzKpfw II Luchs': (2, 6161), 'PzKpfw III/IV': (2, 6417), 'Marder II': (2, 6673), 'Maus': (2, 6929), 'VK4502P (P) Ausf.B': (2, 7441), \
			'Ferdinand': (2, 7697), 'Jagdtiger': (2, 7953), 'Panther II': (2, 8465), 'PzKpfw 38 nA': (2, 8209), 'GW Tiger': (2, 8721), 'GW Panther': (2, 8977), 'GW Typ E': (2, 9233),
			'E-100': (2, 9489), 'E-75': (2, 9745), 'VK2801': (2, 10001), 'E-50': (2, 10257), 'PzKpfw VI Tiger P': (2, 10769), 'JagdPanther II': (2, 11537), 'JagdPz E-100': (2, 12049), \
			'E-50 Ausf.M': (2, 12305), 'PzKpfw V-IV': (2, 51473), 'PzKpfw II Ausf. J': (2, 51729), 'PzKpfw S35 739 (f)': (2, 51985), 'Lowe': (2, 54289), 'T-25': (2, 54545), \
			'8.8 cm Pak 43 JagdTiger': (2, 55313), 'D. Max': (2, 57105), 'D2': (2, 321), 'RenaultBS': (2, 833), 'B1': (2, 1089), 'D1': (2, 1601), '': (2, ), '105 leFH18B2': (2, 2113),\
			'T-15': (2, 54801), 'PzKpfw IV Hydraulic': (2, 55057), 'FCM36 Pak40': (2, 2369), 'ARL 44': (2, 2625), 'AMX 50 100': (2, 3137), 'Bat Chatillon 25t': (2,3649 ), \
			'AMX 50 120': (2, 3905), 'AMX 105AM': (2, 4161), 'AMX 13F3AM': (2, 4673), 'Lorraine39 L AM': (2, 3393), 'AMX 50B': (2, 6209), 'BDR G1B': (2, 6721), \
			'AMX M4 1945': (2, 6977), 'Lorraine155 50': (2, 7233), 'Lorraine155 51': (2, 7489), 'RenaultFT AC': (2, 7745), 'Renault UE 57': (2, 8257), 'Somua S-40': (2, 9793), \
			'S-35 CA': (2, 10049), 'AMX AC Mle.1946': (2, 10817), 'AMX 50 Foch': (2, 11073), 'ARL V39': (2, 11585), 'Bat Chatillon 155': (2, 11841), 'AMX AC Mle. 1948': (2, 12097), \
			'PzKpfw VI Tiger': (2, 529), 'AMX-50 Foch (155)': (2, 13889), 'Type 62': (2, 305)}

#словарь танков и их локализированных названий
TankID = {'MS-1': u'МС-1', 'AT-1': u'АТ-1', 'T-34': u'Т-34', 'IS-3': u'ИС-3', 'IS-4': u'ИС-4', 'KV-1': u'КВ-1', 'KV-2': u'КВ-2',
		'KV-3': u'КВ-3', 'KV-4': u'КВ-4', 'IS': u'ИС', 'IS-8': u'ИС-8', 'SU-8': u'СУ-8', 'IS-7': u'ИС-7', 'SU-5': u'СУ-5',
		'SU-14': u'СУ-14', 'SU-76': u'СУ-76', 'SU-85B': u'СУ-85Б', 'SU-85': u'СУ-85', 'SU-100': u'СУ-100', 'SU-152': u'СУ-152',
		'ISU-152': u'ИСУ-152', 'T-50': u'Т-50', 'T-50-2': u'Т-50-2', 'A-20': u'А-20', 'T-54': u'Т-54', 'BT-2': u'БТ-2',
		'BT-7': u'БТ-7', 'OB704': u'Об. 704', 'OB212': u'Об. 212', 'OB261': u'Об. 261', 'T-46': u'Т-46', 'T-28': u'Т-28',
		'T-43': u'Т-43', 'T-44': u'Т-44', 'T-150': u'Т-150', 'M3St': 'M3 Stuart', 'Type59': 'Type 59', 'AMX1375': 'AMX 13 75', 
		'AMX1390': 'AMX 13 90'}
					
#словарь строк вывода		
outStrings = {'maxFrags': {'ru': u'Больше всего уничтожил за бой:', 'en': 'Max frags:'},}
outStrings['maxXP'] = {'ru': u'Больше всего опыта за бой:', 'en': 'Max XP:'}
outStrings['xp'] = {'ru': u'Опыта заработано:', 'en': 'XP:'}
outStrings['invader'] = {'ru': u'Захватчик:', 'en': 'Invader:'}
outStrings['sniper'] = {'ru': u'Снайпер:', 'en': 'Sniper:'}
outStrings['defender'] = {'ru': u'Защитник:', 'en': 'Defender:'}
outStrings['battlesCount'] = {'ru': u'Количество боев:', 'en': 'Count of battles:'}
outStrings['shots'] = {'ru': u'Выстрелов:', 'en': 'Shots:'}
outStrings['hits'] = {'ru': u'Попаданий:', 'en': 'Hits:'}
outStrings['piercingSeries'] = {'ru': u'Текущая серия пробитий:', 'en': 'Current piercing series:'}
outStrings['maxPiercingSeries'] = {'ru': u'Максимальная серия пробитий:', 'en': 'Max piercing series:'}
outStrings['warrior'] = {'ru': u'Воин:', 'en': 'Warrior:'}
outStrings['killingSeries'] = {'ru': u'Коса смерти (текущее):', 'en': 'Killing series:'}
outStrings['maxKillingSeries'] = {'ru': u'Коса смерти (максимум):', 'en': 'Max killing series:'}
outStrings['maxInvincibleSeries'] = {'ru': u'Максимальная серия побед:', 'en': 'Max invincible series:'}
outStrings['invincibleSeries'] = {'ru': u'Текущая серия invincible:', 'en': 'Current invincible series:'}
outStrings['maxInvincibleSeries'] = {'ru': u'Максимальная серия invincible:', 'en': 'Max invincible series:'}
outStrings['maxSniperSeries'] = {'ru': u'Максимальная серия попаданий:', 'en': 'Max sniper series:'}
outStrings['sniperSeries'] = {'ru': u'Текущая серия попаданий:', 'en': 'Sniper series:'}
outStrings['droppedCapturePoints'] = {'ru': u'Очки защиты базы:', 'en': 'Dropped capture points:'}
outStrings['capturePoints'] = {'ru': u'Очки захвата базы:', 'en': 'Capture points:'}
outStrings['damageReceived'] = {'ru': u'Получил повреждений:', 'en': 'Damage received:'}
outStrings['damageDealt'] = {'ru': u'Нанес повреждений:', 'en': 'Damage dealt:'}
outStrings['fragsBeast'] = {'ru': u'Уничтожил зверей:', 'en': 'Frags beast:'}
outStrings['frags'] = {'ru': u'Танков уничтожил:', 'en': 'Frags:'}
outStrings['winAndSurvived'] = {'ru': u'Выжил в победных боях:', 'en': 'Wins and survived:'}
outStrings['survivedBattles'] = {'ru': u'Выжил в боях:', 'en': 'Survived battles:'}
outStrings['wins'] = {'ru': u'Побед:', 'en': 'Wins:'}
outStrings['losses'] = {'ru': u'Поражений:', 'en': 'Losses:'}
outStrings['battleLifeTime'] = {'ru': u'Времени в боях:', 'en': 'Battle life time:'}
outStrings['lastBattleTime'] = {'ru': u'Последный бой был:', 'en': 'Time of last battle:'}
outStrings['tank'] = {'ru': u'Танк:', 'en': 'Vehicle:'}
outStrings['steelwall'] = {'ru': u'Стальная стена:', 'en': 'Steel wall:'}
outStrings['supporter'] = {'ru': u'Поддержка:', 'en': 'Supporter:'}
outStrings['scout'] = {'ru': u'Разведчик:', 'en': 'Scout:'}
outStrings['evileye'] = {'ru': u'Evileye:', 'en': 'Evileye:'}
outStrings['medalKay'] = {'ru': u'Медаль Кея степени:', 'en': 'Medal Kay'}
outStrings['medalCarius'] = {'ru': u'Медаль Кариуса степени:', 'en': 'Medal Carius'}
outStrings['medalKnispel'] = {'ru': u'Медаль Книспеля степени:', 'en': 'Medal Knispel'}
outStrings['medalPoppel'] = {'ru': u'Медаль Поппеля степени:', 'en': 'Medal Poppel'}
outStrings['spotted'] = {'ru': u'Spotted:', 'en': 'Spotted'}
outStrings['battleHeroes'] = {'ru': u'Герой битвы:', 'en': 'Battle heroes'}
outStrings['maxDiehardSeries'] = {'ru': u'Max diehard series:', 'en': 'Max diehard series'}
outStrings['diehardSeries'] = {'ru': u'Diehard series:', 'en': 'Diehard series'}
outStrings['treesCut'] = {'ru': u'Trees cut:', 'en': 'Trees cut'}
outStrings['medalAbrams'] = {'ru': u'Медаль Абрамса степени:', 'en': 'Medal Abrams'}

outStrings['totalTanks'] = {'ru': u'Обработано записей по танкам:', 'en': 'Tanks stat to out:'}
outStrings['keyError'] = {'ru': u'Ошибка! Неподдерживаемое имя танка.', 'en': 'Error! Unknow name of Tank'}
outStrings['cacheDirNotFound'] = {'ru': u'Ошибка! Директория с файлами кеша WOT не найдена.', 'en': 'Error! Chache dir not found.'}
outStrings['cacheFileNotFound'] = {'ru': u'Ошибка! Файл кеша WOT не найден.', 'en': 'Error! Chache file not found.'}
outStrings['cacheFile'] = {'ru': u'Найден файл кеша:', 'en': 'Chache file found:'}
outStrings['fileDate'] = {'ru': u'Дата файла:', 'en': 'File date:'}
outStrings['fileSave'] = {'ru': u'Записан файл:', 'en': 'File saved:'}

#словарь для сбора данных по всех танках 
xmlData = {}

#help to use
__usage = 'WOT cache parser ver ' + str(__VER__) + '\n' \
	'Usage: \n \
	wot_cache.py [l=ru | l=en] <f=filename | f=cachedir> <out=no | yes> <tank=tank_name>\n \
	l=ru - russian message\n \
	l=en - english message (default)\n \
	filename - full path to WOT cache file\n \
	or filename=cachedir - read the last file from WOT cache dir\n \
	out=no - no out stats to console (default)\n \
	out=yes - out stats to console\n \
	tank= - name of tank to out stats (see tanks.txt for valide tanks names)'
cacheFile = ''

#if program call from command prompt
if __name__ == '__main__': 
	if len(sys.argv) not in (2,3,4,5): print __usage; exit(-1)
	for argv in sys.argv:
		if 'l=' in argv:
			ds = argv.split('=')
			__LANG__ = ds[1]
		if 'f=' in argv:
			ds = argv.split('=')
			cacheFileName = ds[1]
			if ds[1] == 'cachedir': __CACHEDIR__ = True
		if 'out=' in argv:
			ds = argv.split('=')
			if ds[1] == 'yes': __OUTTOCONSOLE__ = True
		if 'tank=' in argv:
			ds = argv.split('=')
			tankToOut = ds[1]
			__ONETANK__ = True

if __ONETANK__ == False:
	if os.path.exists(_txtFile):
		os.remove(_txtFile)

#parse tuple from encoded cache file
def parseString(dataT, bytesA):
	unpackDataTank = struct.unpack('<' + _version + lastBattleTime + battleLifeTime + maxFrags + xp + maxXP + battlesCount + wins + losses + survivedBattles + winAndSurvived + frags + frags8p + \
	fragsBeast + shots + hits + spotted + damageDealt + damageReceived + treesCut + capturePoints + droppedCapturePoints + sniperSeries + maxSniperSeries + invincibleSeries + \
	maxInvincibleSeries + diehardSeries + maxDiehardSeries + killingSeries + maxKillingSeries + piercingSeries + maxPiercingSeries + battleHeroes + warrior + invader + sniper + \
	defender + steelwall + supporter + scout + evileye + medalKay + medalCarius + medalKnispel + medalPoppel + medalAbrams + medalLeClerc + medalLavrinenko + medalEkins + medalWittmann + \
	medalOrlik + medalOskin + medalHalonen + medalBurda + medalBillotte + medalKolobanov + medalFadin + medalRadleyWalters + medalBrunoPietro + medalTarczay + medalPascucci + medalDumitru + \
	medalLehvaslaiho + medalNikolas + medalLafayettePool + beasthunter + mousebane + tankExpert + titleSniper + invincible + diehard + raider + handOfDeath + armorPiercer + kamikaze + \
	lumberjack + markOfMastery + company_xp + company_battlesCount + company_wins + company_losses + company_survivedBattles + company_frags + company_shots + company_hits + company_spotted + \
	company_damageDealt + company_damageReceived + company_capturePoints + clan_xp + clan_battlesCount + clan_wins + clan_losses + clan_survivedBattles + clan_frags + clan_shots + clan_hits + \
	clan_spotted + clan_damageDealt + clan_damageReceived + clan_capturePoints + clan_droppedCapturePoints + str(bytesA) + 'B', dataT)

	return unpackDataTank

def printData(unpackdataTank):
	if unpackDataTank[0] == 17:
		dictkeys = ['_version', 'lastBattleTime', 'battleLifeTime', 'maxFrags', 'xp', 'maxXP', 'battlesCount',
		'wins', 'losses', 'survivedBattles', 'winAndSurvived', 'frags', 'frags8p', 'fragsBeast', 'shots', 'hits',
		'spotted', 'damageDealt', 'damageReceived', 'treesCut', 'capturePoints', 'droppedCapturePoints', 'sniperSeries',
		'maxSniperSeries', 'invincibleSeries', 'maxInvincibleSeries', 'diehardSeries', 'maxDiehardSeries', 'killingSeries',
		'maxKillingSeries', 'piercingSeries', 'maxPiercingSeries', 'battleHeroes', 'warrior', 'invader', 'sniper',
		'defender', 'steelwall', 'supporter', 'scout', 'evileye', 'medalKay', 'medalCarius', 'medalKnispel', 'medalPoppel', 'medalAbrams']
	elif unpackDataTank[0] == 20:
		dictkeys = ['_version', 'lastBattleTime', 'battleLifeTime', 'maxFrags', 'xp', 'maxXP', 'battlesCount',
			'wins', 'losses', 'survivedBattles', 'winAndSurvived', 'frags', 'frags8p', 'fragsBeast', 'shots', 'hits',
			'spotted', 'damageDealt', 'damageReceived', 'treesCut', 'capturePoints', 'droppedCapturePoints', 'sniperSeries',
			'maxSniperSeries', 'invincibleSeries', 'maxInvincibleSeries', 'diehardSeries', 'maxDiehardSeries', 'killingSeries',
			'maxKillingSeries', 'piercingSeries', 'maxPiercingSeries', 'battleHeroes', 'warrior', 'invader', 'sniper',
			'defender', 'steelwall', 'supporter', 'scout', 'evileye', 'medalKay', 'medalCarius', 'medalKnispel', 'medalPoppel', 'medalAbrams']
	elif unpackDataTank[0] == 22:
		dictkeys = ['_version', 'lastBattleTime', 'battleLifeTime', 'maxFrags', 'xp', 'maxXP', 'battlesCount',
			'wins', 'losses', 'survivedBattles', 'winAndSurvived', 'frags', 'frags8p', 'fragsBeast', 'shots', 'hits',
			'spotted', 'damageDealt', 'damageReceived', 'treesCut', 'capturePoints', 'droppedCapturePoints', 'sniperSeries',
			'maxSniperSeries', 'invincibleSeries', 'maxInvincibleSeries', 'diehardSeries', 'maxDiehardSeries', 'killingSeries',
			'maxKillingSeries', 'piercingSeries', 'maxPiercingSeries', 'battleHeroes', 'unknownData1', 'unknownData2', 'warrior', 'invader', 'sniper',
			'defender', 'steelwall', 'supporter', 'scout', 'evileye', 'unknownData3', 'unknownData4', 'medalKay', 'medalCarius', 'medalKnispel', 'medalPoppel', 'medalAbrams']
	else:
		raise Exception('Unknown protocol version %s!' % unpackDataTank[0])
	dictdataTank = dict(zip(dictkeys, unpackdataTank))
	
	if __OUTTOCONSOLE__ == True:
		#print data from tuple to console
		if __DEBUG__:
			print 'Protocol version: %s' % dictdataTank['_version']
			if 'unknownData1' in dictdataTank:
				print 'unknownData1: %s' % dictdataTank['unknownData1']
				print 'unknownData2: %s' % dictdataTank['unknownData2']
				print 'unknownData3: %s' % dictdataTank['unknownData3']
				print 'unknownData4: %s' % dictdataTank['unknownData4']
		lastBattleTime = datetime.datetime.fromtimestamp(dictdataTank['lastBattleTime'])
		print outStrings['lastBattleTime'][__LANG__],  lastBattleTime.strftime('%d.%m.%Y %H:%M')
		print outStrings['battleLifeTime'][__LANG__], str(datetime.timedelta(seconds=int(dictdataTank['battleLifeTime'])))
		print outStrings['maxFrags'][__LANG__], dictdataTank['maxFrags']
		print outStrings['xp'][__LANG__], dictdataTank['xp']
		print outStrings['maxXP'][__LANG__], dictdataTank['maxXP']
		print outStrings['battlesCount'][__LANG__], dictdataTank['battlesCount']
	
		try:
			perWins = dictdataTank['wins']/ (dictdataTank['battlesCount'] / 100.0)
		except ZeroDivisionError:
			perWins = 0
		
		print '%s %s (%s%%)' % (outStrings['wins'][__LANG__], dictdataTank['wins'], int(perWins + 0.5))
	
		try:
			perLosses = dictdataTank['losses']/ (dictdataTank['battlesCount'] / 100.0)
		except ZeroDivisionError:
			perLosses = 0
		
		print '%s %s (%s%%)' % (outStrings['losses'][__LANG__], dictdataTank['losses'], int(perLosses + 0.5))

		try: 
			perSurvivedBattles = dictdataTank['survivedBattles']/ (dictdataTank['battlesCount'] / 100.0)
		except ZeroDivisionError:
			perSurvivedBattles = 0

		print '%s %s (%s%%)' % (outStrings['survivedBattles'][__LANG__], dictdataTank['survivedBattles'], int(perSurvivedBattles + 0.5))

		try:
			perWinAndSurvived = dictdataTank['winAndSurvived']/ (dictdataTank['battlesCount'] / 100.0)
		except ZeroDivisionError:
			perWinAndSurvived = 0

		print '%s %s (%s%%)' % (outStrings['winAndSurvived'][__LANG__], dictdataTank['winAndSurvived'], int(perWinAndSurvived + 0.5))
		print outStrings['frags'][__LANG__], dictdataTank['frags']
		print outStrings['fragsBeast'][__LANG__], dictdataTank['fragsBeast']
		print outStrings['shots'][__LANG__], dictdataTank['shots']
	
		try:
			perHits = dictdataTank['hits']/ (dictdataTank['shots'] / 100.0)
		except ZeroDivisionError:
			perHits = 0
	
		print '%s %s (%s%%)' % (outStrings['hits'][__LANG__], dictdataTank['hits'], int(perHits + 0.5))
		print outStrings['damageDealt'][__LANG__], dictdataTank['damageDealt']
		print outStrings['damageReceived'][__LANG__], dictdataTank['damageReceived']
		print outStrings['capturePoints'][__LANG__], dictdataTank['capturePoints']
		print outStrings['droppedCapturePoints'][__LANG__], dictdataTank['droppedCapturePoints']
		print outStrings['sniperSeries'][__LANG__], dictdataTank['sniperSeries']
		print outStrings['maxSniperSeries'][__LANG__], dictdataTank['maxSniperSeries']
		print outStrings['invincibleSeries'][__LANG__], dictdataTank['invincibleSeries']
		print outStrings['maxInvincibleSeries'][__LANG__], dictdataTank['maxInvincibleSeries']
		print outStrings['killingSeries'][__LANG__], dictdataTank['killingSeries']
		print outStrings['maxKillingSeries'][__LANG__], dictdataTank['maxKillingSeries']
		print outStrings['piercingSeries'][__LANG__], dictdataTank['piercingSeries']
		print outStrings['maxPiercingSeries'][__LANG__], dictdataTank['maxPiercingSeries']
		if dictdataTank['warrior']:
			print outStrings['warrior'][__LANG__], dictdataTank['warrior']
		if dictdataTank['invader']:
			print outStrings['invader'][__LANG__], dictdataTank['invader']
		if dictdataTank['sniper']:
			print outStrings['sniper'][__LANG__], dictdataTank['sniper']
		if dictdataTank['defender']:
			print outStrings['defender'][__LANG__], dictdataTank['defender']
		if dictdataTank['steelwall']:
			print outStrings['steelwall'][__LANG__], dictdataTank['steelwall']
		if dictdataTank['supporter']:
			print outStrings['supporter'][__LANG__], dictdataTank['supporter']
		if dictdataTank['scout']:
			print outStrings['scout'][__LANG__], dictdataTank['scout']
		if dictdataTank['evileye']:
			print outStrings['evileye'][__LANG__], dictdataTank['evileye']
		if dictdataTank['medalKay']:
			print outStrings['medalKay'][__LANG__], dictdataTank['medalKay']
		if dictdataTank['medalCarius']:
			print outStrings['medalCarius'][__LANG__], dictdataTank['medalCarius']
		if dictdataTank['medalKnispel']:
			print outStrings['medalKnispel'][__LANG__], dictdataTank['medalKnispel']
		if dictdataTank['medalPoppel']:
			print outStrings['medalPoppel'][__LANG__], dictdataTank['medalPoppel']
		if dictdataTank['medalAbrams']:
			print outStrings['medalAbrams'][__LANG__], dictdataTank['medalAbrams']
		
	return dictdataTank
	
#save data to TXT file
def saveTxtFile(dDataTank, vehicle):
	file = open(_txtFile, 'a')
	strVehicle = ' *** ' + outStrings['tank'][__LANG__] + ' ' + vehicle + ' *** \n'
	file.write(strVehicle.encode('utf-8'))
	lastBattleTime = datetime.datetime.fromtimestamp(dDataTank['lastBattleTime'])
	strToWrite = outStrings['battleLifeTime'][__LANG__] + ' ' + str(datetime.timedelta(seconds=int(dDataTank['battleLifeTime']))) + '\n'
	strToWrite += outStrings['lastBattleTime'][__LANG__] + ' ' + str(lastBattleTime.strftime('%d.%m.%Y %H:%M')) + '\n'
	strToWrite += outStrings['battlesCount'][__LANG__] + ' ' + str(dDataTank['battlesCount']) + '\n'
	
	try:
		perWins = dDataTank['wins']/ (dDataTank['battlesCount'] / 100.0)
	except ZeroDivisionError:
		perWins = 0
		
	strToWrite += outStrings['wins'][__LANG__] + ' ' + str(dDataTank['wins']) + ' (' + str(int(perWins + 0.5)) + '%)\n'
	strToWrite += outStrings['losses'][__LANG__] + ' ' + str(dDataTank['losses']) + '\n'
	strToWrite += outStrings['survivedBattles'][__LANG__] + ' ' + str(dDataTank['survivedBattles']) + '\n'
	strToWrite += outStrings['winAndSurvived'][__LANG__] + ' ' + str(dDataTank['winAndSurvived']) + '\n'
	strToWrite += outStrings['frags'][__LANG__] + ' ' + str(dDataTank['frags']) + '\n'
	strToWrite += outStrings['shots'][__LANG__] + ' ' + str(dDataTank['shots']) + '\n'
	
	try:
		perHits = dDataTank['hits']/ (dDataTank['shots'] / 100.0)
	except ZeroDivisionError:
		perHits = 0
		
	strToWrite += outStrings['hits'][__LANG__] + ' ' + str(dDataTank['hits']) + ' (' + str(int(perHits + 0.5)) + '%)\n'
	strToWrite += outStrings['damageDealt'][__LANG__] + ' ' + str(dDataTank['damageDealt']) + '\n'
	strToWrite += outStrings['damageReceived'][__LANG__] + ' ' + str(dDataTank['damageReceived']) + '\n'
	strToWrite += outStrings['capturePoints'][__LANG__] + ' ' + str(dDataTank['capturePoints']) + '\n'
	strToWrite += outStrings['droppedCapturePoints'][__LANG__] + ' ' + str(dDataTank['droppedCapturePoints']) + '\n'
	strToWrite += outStrings['sniperSeries'][__LANG__] + ' ' + str(dDataTank['sniperSeries']) + '\n'
	strToWrite += outStrings['maxSniperSeries'][__LANG__] + ' ' + str(dDataTank['maxSniperSeries']) + '\n'
	strToWrite += outStrings['invincibleSeries'][__LANG__] + ' ' + str(dDataTank['invincibleSeries']) + '\n'
	strToWrite += outStrings['maxInvincibleSeries'][__LANG__] + ' ' + str(dDataTank['maxInvincibleSeries']) + '\n'
	strToWrite += outStrings['diehardSeries'][__LANG__] + ' ' + str(dDataTank['diehardSeries']) + '\n'
	strToWrite += outStrings['maxDiehardSeries'][__LANG__] + ' ' + str(dDataTank['maxDiehardSeries']) + '\n'
	strToWrite += outStrings['killingSeries'][__LANG__] + ' ' + str(dDataTank['killingSeries']) + '\n'
	strToWrite += outStrings['maxKillingSeries'][__LANG__] + ' ' + str(dDataTank['maxKillingSeries']) + '\n'
	strToWrite += outStrings['piercingSeries'][__LANG__] + ' ' + str(dDataTank['piercingSeries']) + '\n'
	strToWrite += outStrings['maxPiercingSeries'][__LANG__] + ' ' + str(dDataTank['maxPiercingSeries']) + '\n'
	strToWrite += outStrings['battleHeroes'][__LANG__] + ' ' + str(dDataTank['battleHeroes']) + '\n'
	strToWrite += outStrings['warrior'][__LANG__] + ' ' + str(dDataTank['warrior']) + '\n'
	strToWrite += outStrings['invader'][__LANG__] + ' ' + str(dDataTank['invader']) + '\n'
	strToWrite += outStrings['sniper'][__LANG__] + ' ' + str(dDataTank['sniper']) + '\n'
	strToWrite += outStrings['defender'][__LANG__] + ' ' + str(dDataTank['defender']) + '\n'
	strToWrite += outStrings['steelwall'][__LANG__] + ' ' + str(dDataTank['steelwall']) + '\n'
	strToWrite += outStrings['supporter'][__LANG__] + ' ' + str(dDataTank['supporter']) + '\n'
	if dDataTank['warrior']:
			strToWrite += outStrings['warrior'][__LANG__] + ' ' + str(dDataTank['warrior']) + '\n'
	if dDataTank['invader']:
		strToWrite += outStrings['invader'][__LANG__] + ' ' + str(dDataTank['invader']) + '\n'
	if dDataTank['sniper']:
		strToWrite += outStrings['sniper'][__LANG__] + ' ' + str(dDataTank['sniper']) + '\n'
	if dDataTank['defender']:
		strToWrite += outStrings['defender'][__LANG__] + ' ' + str(dDataTank['defender']) + '\n'
	if dDataTank['steelwall']:
		strToWrite += outStrings['steelwall'][__LANG__] + ' ' + str(dDataTank['steelwall']) + '\n'
	if dDataTank['supporter']:
		strToWrite += outStrings['supporter'][__LANG__] + ' ' + str(dDataTank['supporter']) + '\n'
	if dDataTank['scout']:
		strToWrite += outStrings['scout'][__LANG__] + ' ' + str(dDataTank['scout']) + '\n'
	if dDataTank['evileye']:
		strToWrite += outStrings['evileye'][__LANG__] + ' ' + str(dDataTank['evileye']) + '\n'
	if dDataTank['medalKay']:
		strToWrite += outStrings['medalKay'][__LANG__] + ' ' + str(dDataTank['medalKay']) + '\n'
	if dDataTank['medalCarius']:
		strToWrite += outStrings['medalCarius'][__LANG__] + ' ' + str(dDataTank['medalCarius']) + '\n'
	if dDataTank['medalKnispel']:
		strToWrite += outStrings['medalKnispel'][__LANG__] + ' ' + str(dDataTank['medalKnispel']) + '\n'
	if dDataTank['medalPoppel']:
		strToWrite += outStrings['medalPoppel'][__LANG__] + ' ' + str(dDataTank['medalPoppel']) + '\n'
	file.write(strToWrite.encode('utf-8'))
	split = '-------------------------\n\n'
	file.write(split.encode('utf-8'))
	file.close()
	return True

#запись в XML файл
def saveXMLFile():
	file = open(_xmlFile, 'w')
	strToWrite = '<?xml version=\'1.0\' encoding=\'utf-8\'?>\n'
	strToWrite += '<WOTCacheStats ver=\'' + str(__VER__) + '\'>\n'
	file.write(strToWrite.encode('utf-8'))
	for tank in xmlData:
		strToWrite = '\t<tank>\n'
		strToWrite += '\t\t<name>%s</name>\n' % tank
		strToWrite += '\t\t<battleLifeTime>%s</battleLifeTime>\n' % datetime.timedelta(seconds=int(xmlData[tank]['battleLifeTime']))
		lastBattleTime = datetime.datetime.fromtimestamp(xmlData[tank]['lastBattleTime'])
		strToWrite += '\t\t<lastBattleTime>%s</lastBattleTime>\n' % lastBattleTime.strftime('%d.%m.%Y %H:%M')
		strToWrite += '\t\t<battlesCount>%s</battlesCount>\n' % xmlData[tank]['battlesCount']
		strToWrite += '\t\t<wins>%s</wins>\n' % xmlData[tank]['wins']
		strToWrite += '\t\t<losses>%s</losses>\n' % xmlData[tank]['losses']
		strToWrite += '\t\t<survivedBattles>%s</survivedBattles>\n' % xmlData[tank]['survivedBattles']
		strToWrite += '\t\t<winAndSurvived>%s</winAndSurvived>\n' % xmlData[tank]['winAndSurvived']
		strToWrite += '\t\t<frags>%s</frags>\n' % xmlData[tank]['frags']
		strToWrite += '\t\t<shots>%s</shots>\n' % xmlData[tank]['shots']
		strToWrite += '\t\t<shots>%s</shots>\n' % xmlData[tank]['shots']
		strToWrite += '\t\t<hits>%s</hits>\n' % xmlData[tank]['hits']
		strToWrite += '\t\t<damageDealt>%s</damageDealt>\n' % xmlData[tank]['damageDealt']
		strToWrite += '\t\t<damageReceived>%s</damageReceived>\n' % xmlData[tank]['damageReceived']
		strToWrite += '\t\t<capturePoints>%s</capturePoints>\n' % xmlData[tank]['capturePoints']
		strToWrite += '\t\t<droppedCapturePoints>%s</droppedCapturePoints>\n' % xmlData[tank]['droppedCapturePoints']
		strToWrite += '\t\t<sniperSeries>%s</sniperSeries>\n' % xmlData[tank]['sniperSeries']
		strToWrite += '\t\t<maxSniperSeries>%s</maxSniperSeries>\n' % xmlData[tank]['maxSniperSeries']
		strToWrite += '\t\t<invincibleSeries>%s</invincibleSeries>\n' % xmlData[tank]['invincibleSeries']
		strToWrite += '\t\t<maxInvincibleSeries>%s</maxInvincibleSeries>\n' % xmlData[tank]['maxInvincibleSeries']
		strToWrite += '\t\t<diehardSeries>%s</diehardSeries>\n' % xmlData[tank]['diehardSeries']
		strToWrite += '\t\t<maxDiehardSeries>%s</maxDiehardSeries>\n' % xmlData[tank]['maxDiehardSeries']
		strToWrite += '\t\t<killingSeries>%s</killingSeries>\n' % xmlData[tank]['killingSeries']
		strToWrite += '\t\t<maxKillingSeries>%s</maxKillingSeries>\n' % xmlData[tank]['maxKillingSeries']
		strToWrite += '\t\t<piercingSeries>%s</piercingSeries>\n' % xmlData[tank]['piercingSeries']
		strToWrite += '\t\t<maxPiercingSeries>%s</maxPiercingSeries>\n' % xmlData[tank]['maxPiercingSeries']
		strToWrite += '\t\t<battleHeroes>%s</battleHeroes>\n' % xmlData[tank]['battleHeroes']
		strToWrite += '\t\t<warrior>%s</warrior>\n' % xmlData[tank]['warrior']
		strToWrite += '\t\t<invader>%s</invader>\n' % xmlData[tank]['invader']
		strToWrite += '\t\t<sniper>%s</sniper>\n' % xmlData[tank]['sniper']
		strToWrite += '\t\t<defender>%s</defender>\n' % xmlData[tank]['defender']
		strToWrite += '\t\t<steelwall>%s</steelwall>\n' % xmlData[tank]['steelwall']
		strToWrite += '\t\t<supporter>%s</supporter>\n' % xmlData[tank]['supporter']
		strToWrite += '\t\t<warrior>%s</warrior>\n' % xmlData[tank]['warrior']
		strToWrite += '\t\t<invader>%s</invader>\n' % xmlData[tank]['invader']
		strToWrite += '\t\t<sniper>%s</sniper>\n' % xmlData[tank]['sniper']
		strToWrite += '\t\t<defender>%s</defender>\n' % xmlData[tank]['defender']
		strToWrite += '\t\t<steelwall>%s</steelwall>\n' % xmlData[tank]['steelwall']
		strToWrite += '\t\t<supporter>%s</supporter>\n' % xmlData[tank]['supporter']
		strToWrite += '\t\t<scout>%s</scout>\n' % xmlData[tank]['scout']
		strToWrite += '\t\t<evileye>%s</evileye>\n' % xmlData[tank]['evileye']
		strToWrite += '\t\t<medalKay>%s</medalKay>\n' % xmlData[tank]['medalKay']
		strToWrite += '\t\t<medalCarius>%s</medalCarius>\n' % xmlData[tank]['medalCarius']
		strToWrite += '\t\t<medalKnispel>%s</medalKnispel>\n' % xmlData[tank]['medalKnispel']
		strToWrite += '\t\t<medalKnispel>%s</medalKnispel>\n' % xmlData[tank]['medalPoppel']
		
		strToWrite += '\t</tank>\n'
		file.write(strToWrite.encode('utf-8'))
	strToWrite = '</WOTCacheStats>'
	file.write(strToWrite.encode('utf-8'))
	file.close()
	print outStrings['fileSave'][__LANG__], _xmlFile, '\n'
	
#if need parse file in WOT cache dir
if __CACHEDIR__ == True:
	Environ = os.environ
	appData = Environ['APPDATA']
	pathToCache = appData + '\\wargaming.net\\WorldOfTanks\\dossier_cache\\'
	if os.path.exists(pathToCache):
		cacheFiles = os.listdir(pathToCache)
		time1 = os.path.getmtime(pathToCache + cacheFiles[0])
		cacheFileName = pathToCache + cacheFiles[0]
		if os.path.exists(cacheFileName) != True:
			outStrings['cacheFileNotFound'][__LANG__]
			exit(0)
		for fl in cacheFiles:
			if os.path.getmtime(pathToCache + fl) > time1:
				time1 = os.path.getmtime(pathToCache + fl)
				cacheFileName = pathToCache + fl
		print '\n', outStrings['cacheFile'][__LANG__], cacheFileName, '\n'
		time1 = datetime.datetime.fromtimestamp(time1)
		print outStrings['fileDate'][__LANG__], time1.strftime('%d.%m.%Y %H:%M'), '\n'
	else:
		print outStrings['cacheDirNotFound'][__LANG__]
		exit(0)

cacheFile = open(cacheFileName, 'rb')
cacheData = pickle.load(cacheFile)
cacheFile.close()

cacheDict = cacheData[1]
podstLen = 266

#если надо вывести статистику по одному танку
if tankToOut != '':
	__OUTTOCONSOLE__ = True
	tankToOut = TankID.get(tankToOut, tankToOut)
	try:
		timeTank = cacheDict[tanksID[tankToOut]][0]
		dataTank = cacheDict[tanksID[tankToOut]][1]
		dataLen = len(dataTank)
		bytesAdd = dataLen - podstLen
		unpackDataTank = parseString(dataTank, bytesAdd)
		unpackDataTank = list(unpackDataTank)
		print outStrings['tank'][__LANG__], tankToOut
		dictData = printData(unpackDataTank)
	except KeyError:
		print outStrings['keyError'][__LANG__]
else:
	#цикл по имеющимся ID танков
	for key in tanksID:
		try:
			timeTank, dataTank = cacheDict[tanksID[key]]
		except KeyError:
			continue
		totalTanks += 1
		if __OUTTOCONSOLE__ == True:
			print outStrings['tank'][__LANG__], key
		dataLen = len(dataTank)
		bytesAdd = dataLen - podstLen
		unpackDataTank = parseString(dataTank, bytesAdd)
		unpackDataTank = list(unpackDataTank)
		dictData = printData(unpackDataTank)
		saveToFileMes = saveTxtFile(dictData, key)
		xmlData[key] = dictData
		if __OUTTOCONSOLE__ == True:
			print '---------------------\n'
	
	print outStrings['totalTanks'][__LANG__], totalTanks, '\n'
	
	if saveToFileMes == True: print outStrings['fileSave'][__LANG__], _txtFile, '\n'
	saveXMLFile()


